<template>
  <div>
    <el-card>

      <!--搜索框与按钮-->
      <el-row :gutter="20">
        <el-col :span="8">

          <el-input placeholder="输入关键字查询"
                    v-model="queryInfo.query"
                    clearable
                    @clear="getTableList">
            <el-button slot="append"
                       icon="el-icon-search"
                       @click="getTableList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="3">
          <el-button type="primary"
                     @click="addDialogVisible=true"
                     icon="el-icon-circle-plus-outline"
                     style="width:100%">新增</el-button>
        </el-col>
        <el-col :span="3">
          <el-button type="danger"
                     @click="deleteRecordByIds"
                     icon="el-icon-remove-outline"
                     style="width:100%">批量删除</el-button>
        </el-col>
        <el-col :span="3">
          <el-button type="success"
                     @click="deleteRecordByIds"
                     icon="el-icon-download"
                     style="width:100%">导出EXCEL</el-button>
        </el-col>
      </el-row>

      <!-- 排版日历 -->
      <el-calendar>
        <template slot="dateCell"
                  slot-scope="{ date,data}">
          <div @click="arrangeDialog(date,data)">
            <p :class="data.isSelected ? 'is-selected' : ''">
              {{ data.day.split('-').slice(1).join('-') }} {{ data.isSelected ? '✔️' : ''}}
            </p>
          </div>
        </template>
      </el-calendar>
      <!-- <el-calendar v-model="currentDay"
                   @click="arrangeDialog(date,data)">
      </el-calendar> -->

      <!-- 点击按钮的弹出框以及详细信息抽屉区域 -->
      <el-drawer title="我是标题"
                 :visible.sync="drawerVisible"
                 :with-header="false">
        <span>我来啦!</span>
      </el-drawer>
      <!-- 添加记录的对话框 -->
      <el-dialog title="添加记录"
                 :visible.sync="addDialogVisible"
                 @close="addDialogClosed"
                 width="50%">
        <!-- 内容主体区 -->
        <el-form :model="addForm"
                 :rules="addFormRules"
                 ref="addFormRef"
                 label-width="90px">
          <el-form-item label="编号"
                        prop="id">
            <el-input v-model="addForm.id"
                      disabled></el-input>
          </el-form-item>
          <el-form-item label="日期"
                        prop="arrangeDate">
            <el-input v-model="addForm.arrangeDate"></el-input>
          </el-form-item>
          <el-form-item label="工作时段"
                        prop="workTime">
            <el-input v-model="addForm.workTime"></el-input>
          </el-form-item>
          <el-form-item label="小组名"
                        prop="groupName">
            <el-input v-model="addForm.groupName"></el-input>
          </el-form-item>
          <el-form-item label="巡逻线路id"
                        prop="rounteId">
            <el-input v-model="addForm.rounteId"></el-input>
          </el-form-item>

        </el-form>
        <!-- 底部区域 -->
        <span slot="footer"
              class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary"
                     @click="addRecord">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 排班对话框 -->
      <el-dialog title="巡逻排班"
                 :visible.sync="arrangeDialogVisible"
                 @close="arrangeDialogClosed"
                 width="50%">
        <!-- 内容主体区 -->
        <el-tabs type="border-card">
          <el-tab-pane label="早班排班">
            <el-form :model="arrangeForm"
                     ref="arrangeFormRef"
                     label-width="90px"
                     class="demo-dynamic">

              <!-- <el-col :span="12">
                  <el-form-item prop="email"
                                label="邮箱"
                                :rules="[
                            { required: true, message: '请输入邮箱地址', trigger: 'blur' },
                            { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
              ]">
                    <el-input v-model="arrangeForm.email"></el-input>
                  </el-form-item>
                </el-col> -->

              <el-card v-for="(item, index) in arrangeForm.domains"
                       :key="item.key">
                <el-row>
                  <el-col :span="10">
                    <el-form-item :label="index+'巡逻路线'"
                                  :key="item.key"
                                  :prop="'domains.' + index + '.rounteId'"
                                  :rules="{
                              required: true, message: '巡逻路线不能为空', trigger: 'blur'
                             }">

                      <el-input v-model="item.rounteId"
                                placeholder="请选择巡逻路线ID"></el-input>

                    </el-form-item>
                  </el-col>
                  <el-col :span="10">

                    <el-form-item :label="'巡逻小组' "
                                  :key="item.key"
                                  :prop="'domains.' + index + '.groupId'"
                                  :rules="{
                              required: true, message: '巡逻小组内容不能为空', trigger: 'blur'
                             }">

                      <el-input v-model="item.groupId"
                                placeholder="请选择小组ID"></el-input>

                    </el-form-item>
                  </el-col>

                  <el-col :span="3"
                          :offset="1">
                    <el-button @click.prevent="removeDomain(domain)">删除</el-button>

                  </el-col>
                  <!-- <el-form-item v-for="(domain, index) in arrangeForm.domains"
                            :label="'排班' + index"
                            :key="domain.key"
                            :prop="'domains.' + index + '.value'"
                            :rules="{
                              required: true, message: '排班内容不能为空', trigger: 'blur'
                             }">
                <el-row>
                  <el-col :span="9">
                    <el-input v-model="domain.rounteId"
                              placeholder="请选择巡逻路线ID"></el-input>
                  </el-col>
                  <el-col :span="9">
                    <el-input v-model="domain.groupId"
                              placeholder="请选择小组ID"></el-input>
                  </el-col>

                  <el-col :span="6">
                    <el-button @click.prevent="removeDomain(domain)">删除</el-button>
                  </el-col>
                </el-row>

              </el-form-item> -->
                </el-row>
              </el-card>

              <el-form-item>
                <el-button type="primary"
                           @click="submitForm()">提交</el-button>
                <el-button @click="addDomain">新增排班</el-button>
                <el-button @click="resetForm('arrangeForm')">重置</el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="午班排班">配置管理</el-tab-pane>
          <el-tab-pane label="晚班排班">角色管理</el-tab-pane>

        </el-tabs>
        <!-- 底部区域 -->
        <span slot="footer"
              class="dialog-footer">
          <el-button @click="arrangeDialogVisible = false">取 消</el-button>
          <el-button type="primary"
                     @click="addRecord">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改记录对话框 -->
      <el-dialog title="修改记录"
                 :visible.sync="editDialogVisible"
                 width="50%"
                 @close="editDialogClosed">
        <el-form :model="editForm"
                 :rules="editFormRules"
                 ref="editFormRef"
                 label-width="90px">

          <el-form-item label="编号"
                        prop="id">
            <el-input v-model="editForm.id"></el-input>
          </el-form-item>
          <el-form-item label="日期"
                        prop="arrangeDate">
            <el-input v-model="editForm.arrangeDate"></el-input>
          </el-form-item>
          <el-form-item label="工作时段"
                        prop="workTime">
            <el-input v-model="editForm.workTime"></el-input>
          </el-form-item>
          <el-form-item label="小组名"
                        prop="groupName">
            <el-input v-model="editForm.groupName"></el-input>
          </el-form-item>
          <el-form-item label="巡逻线路id"
                        prop="rounteId">
            <el-input v-model="editForm.rounteId"></el-input>
          </el-form-item>

        </el-form>
        <span slot="footer"
              class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary"
                     @click="editRecordInfo">确 定</el-button>
        </span>
      </el-dialog>

    </el-card>
  </div>
</template>
<script>
import {
  getList,
  add,
  deleteSelected,
  deleteCurrent,
  getEditInfo,
  edit,
  getDetail,
  modifySwitch,
} from "@/api/logistics/logisticsGreen.js";
export default {
  data () {
    return {
      // 表格列筛选数据
      tableFilterData: {
        dataList: [
          {
            id: "1001",
            arrangeDate: "2019-6-19",
            workTime: "0",
            groupName: "第一组",
            rounteId: "1001"
          },
          {
            id: "1002",
            arrangeDate: "2019-6-19",
            workTime: "1",
            groupName: "第二组",
            rounteId: "1002"
          },
          {
            id: "1003",
            arrangeDate: "2019-6-19",
            workTime: "2",
            groupName: "第三组",
            rounteId: "1003"
          },
        ],
        dataNow: [
          { label: "编号", attr: "id", checked: true },
          { label: "日期", attr: "arrangeDate", checked: true },
          { label: "工作时段", attr: "workTime", checked: true },
          { label: "小组名", attr: "groupName", checked: true },
          { label: "巡逻线路id", attr: "rounteId", checked: true },

        ],

        checkLabels: [], // 筛选列显示多选框数据
        checkBoxList: [], // 筛选列数据
        indexTwo: 0,
      },
      // 记录列表分页区的参数
      queryInfo: {
        //搜索条件
        query: "",
        // 当前页码
        pagenum: 1,
        //每页显示条数
        pagesize: 7,
      },
      total: 24,


      // 控制添加记录对话框的显示与隐藏
      addDialogVisible: false,
      // 添加记录的表单数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 添加表单校验规则
      addFormRules: {},

      // 控制编辑当前日期的排班对话框的显示与隐藏
      arrangeDialogVisible: false,
      //查询到的当前日期的排班情况
      arrangeForm: {
        shows: [{
          id: '',
          arrangeDate: '',
          workTime: '',
          groupName: '',
          rounteId: 'xxx',
          groupId: 'xxx',
        },],
        domains: [{
          value: '',
          rounteId: 'xxx',
          groupId: 'xxx',
        }, {
          value: 'temp',
          rounteId: '',
          groupId: '',
        }],
        email: ''
      },


      //排班表单的校验规则
      arrangeFormRules: {},


      // 控制修改用户对话框的显示与隐藏
      editDialogVisible: false,
      // 查询到的用户信息
      editForm: {},
      // 编辑表单校验规则
      editFormRules: {},


      // 控制详细信息抽屉的显示与隐藏
      drawerVisible: false,
      // 详细信息的表单数据
      detailForm: {},
      // 被选中的记录id
      selectedList: [],

      currentDayInfo: {},
      workTime: '',
    }
  },
  created () {

  },
  methods: {
    // 获取列表信息
    async getTableList () {
      await getList(
        this.queryInfo.pagenum,
        this.queryInfo.pagesize,
        this.queryInfo.query
      ).then((res) => {
        if (res.data.code !== 200) {
          return this.$message.error('获取表格数据失败!')
        }
        this.tableList = res.data.data.list
        this.total = res.data.data.total

        console.log(res)
      })

    },

    // 监听多选框选中的所有记录
    handleSelectionChange (val) {
      this.selectedList = val;
    },
    // 监听pagesize改变的事件
    handleSizeChange (newSize) {
      console.log(newSize)
      this.queryinfo.pagesize = newSize
      this.getTableList()
    },
    // 监听页码值改变的事件
    handleCurrentChange (newPage) {
      console.log(newPage)
      this.queryinfo.pagenum = newPage
      this.getTableList()
    },
    // 监听添加对话框的关闭事件
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },
    // 监听排班对话框的关闭事件
    arrangeDialogClosed () {
      this.$refs.arrangeFormRef.resetFields()
    },
    // 监听修改对话框的关闭
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },
    // 表头列筛选功能
    filterFunHandle (type, currentItem, index) {
      if (type === 'filter') { // 筛选列
        if (event.target.checked === false) {
          this.tableFilterData.dataNow.forEach((item, index, arr) => {
            if (item.attr === currentItem) {
              return item.checked = false
            }
          })
        } else {
          this.tableFilterData.dataNow.forEach((item, index, arr) => {
            if (item.attr === currentItem) {
              return item.checked = true
            }
          })
        }
      } else if (type === 'allchecked') { // 全选
        if (this.tableFilterData.checkLabels.length === 0) {
          this.tableFilterData.dataNow.forEach((result) => {
            this.tableFilterData.checkLabels.push(result.attr)
          })
          this.tableFilterData.checkBoxList = this.tableFilterData.checkLabels // 复选框置为复选所有值，全部选择    
        } else {
          this.tableFilterData.checkBoxList = this.tableFilterData.checkLabels // 复选框置为复选所有值，全部选择
        }
        this.tableFilterData.dataNow.forEach((item, index, arr) => {
          item.checked = true
        })
      } else if (type === 'cancel') { // 取消全选
        this.tableFilterData.checkBoxList = [] // 复选框置为空，全部不选择
        this.tableFilterData.dataNow.forEach((item, index, arr) => {
          item.checked = false
        })
      }
    },
    // 类型筛选（标签筛选）
    filterType (value, row) {
      return row.workTime === value;
    },






    // 添加记录
    addRecord () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        // 可以发起添加记录的网络请求
        await add(
          this.addForm.name,
          this.addForm.password,
          this.addForm.phone,
          this.addForm.roleId
        ).then((res) => {
          if (res.meta.status !== 201) {
            this.$message.error('添加记录失败！')
          }
          this.$message.success('添加记录成功！')
          // 隐藏添加记录的对话框
          this.addDialogVisible = false
          // 重新获取记录列表数据
          this.getTableList()
        })
      })
    },
    // 删除（批量）
    async deleteRecordByIds () {
      // 弹框询问用户是否删除数据
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 如果用户确认删除，返回值为字符串confirm
      // 如果用户取消删除，返回值未字符串cancel
      // console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消删除')
      }
      await deleteSelected(this.selectedList).then((res) => {
        if (res.meta.status !== 200) {
          return this.$message.error('删除记录失败！')
        }
        this.$message.success('删除记录成功！')
        this.getTableList()
      })

    },
    // 查看修改记录（当前记录）
    async showEditDialog (rowInfo) {
      this.editForm = rowInfo
      this.editDialogVisible = true
    },
    // 确认修改
    editRecordInfo () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        // 发起修改记录信息的数据请求
        await edit(
          this.editForm.id,
          this.editForm.email,
          this.editForm.mobile
        ).then((res) => {
          if (res.meta.status !== 200) {
            return this.$message.error('更新信息失败！')
          }
          // 关闭对话框
          this.editDialogVisible = false
          // 刷新数据列表
          this.getTableList()
          // 提示修改成功
          this.$message.success('更新信息成功！')
        })

      })
    },
    // 删除（当前记录）
    async deleteRecordById (id) {
      // 弹框询问用户是否删除数据
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 如果用户确认删除，返回值为字符串confirm
      // 如果用户取消删除，返回值未字符串cancel
      // console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消删除')
      }
      await deleteCurrent(id).then((res) => {
        if (res.meta.status !== 200) {
          return this.$message.error('删除记录失败！')
        }
        this.$message.success('删除记录成功！')
        this.getTableList()
      })

    },
    // 查看详情（当前记录）
    async getDetailInfo (rowInfo) {
      this.detailForm = rowInfo
      this.drawerVisible = true
    },
    // 修改switch开关状态（当前记录）
    async switchStateChanged (userinfo) {
      console.log(userinfo)
      await modifySwitch(userinfo.id, userinfo.state).then((res) => {
        if (res.data.code !== 200) {
          userinfo.mg_state = !userinfo.mg_state
          return this.$message.error('更新状态失败!')
        }
        this.$message.success('更新状态成功!')
      })

    },
    arrangeDialog (date, data) {
      console.log(date)
      console.log(data)
      this.currentDayInfo = data
      this.arrangeDialogVisible = !this.arrangeDialogVisible

    },
    // 提交表单新增多条排版记录
    submitForm () {
      this.$refs.arrangeFormRef.validate(async valid => {
        if (!valid) return this.$message.error("存在排班信息未完善！请完善排班信息或删除该条排班记录")
        const { data: res } = await this.$http.post("xxxAction/addObject", { arrangeDate: this.currentDayInfo.day, workTime: this.workTime, })
        if (!res.success) return this.$message.error('添加失败')
        this.$message.success('添加记录成功！')
        // 隐藏添加记录的对话框
        this.addDialogVisible = false
        // 重新获取记录列表数据
        this.getTableList()
      })
      this.$refs.arrangeFormRef.validate((valid) => {
        if (valid) {
          alert('submit!');
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm () {
      this.$refs.arrangeFormRef.resetFields();
    },
    removeDomain (item) {
      var index = this.arrangeForm.domains.indexOf(item)
      if (index !== -1) {
        this.arrangeForm.domains.splice(index, 1)
      }
    },
    addDomain () {
      this.arrangeForm.domains.push({
        value: '',
        rounteId: '',
        groupId: '',
        key: Date.now()
      });
    }

  }

}


</script>
<style scoped>
.el-table {
  font-size: 13px;
}
.el-pagination {
  text-align: left;
  padding-top: 20px;
}
.is-selected {
  color: #1989fa;
}
</style>